import com.google.common.io.Files
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
import java.nio.charset.StandardCharsets
import java.text.SimpleDateFormat


import groovy.transform.SourceURI
import java.nio.file.Path
import java.nio.file.Paths

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */

packageName = "com.sample;"

//db/java类型匹配模式
typeMapping = [
        (~/(?i)int/)                      : "long",
        (~/(?i)float|double|decimal|real/): "double",
        (~/(?i)decimal/): "BigDecimal",
        (~/(?i)datetime|timestamp/)       : "java.sql.Timestamp",
        (~/(?i)date/)                     : "java.sql.Date",
        (~/(?i)time/)                     : "java.sql.Time",
        (~/(?i)/)                         : "String"
]
//db规则匹配模式
dbTypeMapping = [
        (~/(?i)tinyint/)                  : "tinyint",
        (~/(?i)smallint/)                 : "smallint",
        (~/(?i)mediumint/)                : "mediumint",
        (~/(?i)bigint/)                   : "bigint",
        (~/(?i)int/)                      : "int",
        (~/(?i)float/)                    : "float",
        (~/(?i)double/)                   : "double",
        (~/(?i)decimal/)                  : "decimal",
        (~/(?i)real/)                     : "real",
        (~/(?i)decimal/)                  : "decimal",
        (~/(?i)timestamp/)                : "timestamp",
        (~/(?i)datetime/)                 : "datetime",
        (~/(?i)date/)                     : "date",
        (~/(?i)time/)                     : "time",
        (~/(?i)bit/)                     : "bit",
        (~/(?i)blob/)                     : "blob",
        (~/(?i)/)                         : "text"
]

dbUnsignedMapping = [
        (~/(?i)unsigned/)               : true
]

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
    SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
    def className = javaName(table.getName(), true)
    def fields = calcFields(table)
    new File(dir, className + "Controller.java").withPrintWriter { out -> generate(out, className, fields, dir, table) }
}

def generate(out, className, fields, dir, table) {
    packageName = findPackageName(dir)
    def domainPackageName = findDomainPackageName(dir)
    def servicePackageName = findServicePackageName(dir)
    def fastLowerClassName = toLowerCaseFirstOne(className)
    def userName = System.getProperty( "user.name")
    def currentDate = currentDate()
    //读取表备注
    def tableComment = table.getComment()
    if(tableComment == null || tableComment == '') {
        tableComment = table.getName()
    }
    if(packageName != "") out.println("package $packageName;\n")
    out.print(
                    "import java.time.LocalDateTime;\n"+
                    "import work.soho.common.core.util.PageUtils;\n"+
                    "import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;\n" +
                    "import java.util.*;\n" +
                    "import lombok.RequiredArgsConstructor;\n" +
                    "import org.springframework.web.bind.annotation.GetMapping;\n" +
                    "import org.springframework.web.bind.annotation.PostMapping;\n" +
                    "import org.springframework.web.bind.annotation.PutMapping;\n" +
                    "import org.springframework.web.bind.annotation.DeleteMapping;\n" +
                    "import org.springframework.web.bind.annotation.PathVariable;\n" +
                    "import org.springframework.web.bind.annotation.RequestBody;\n" +
                    "import org.springframework.web.bind.annotation.RequestMapping;\n" +
                    "import org.springframework.web.bind.annotation.RestController;\n" +
                    "import work.soho.common.core.util.StringUtils;\n" +
                    "import com.github.pagehelper.PageSerializable;\n" +
                    "import work.soho.common.core.result.R;\n" +
                    "import work.soho.api.admin.annotation.Node;\n"+
                    "import ${domainPackageName}.${className};\n" +
                    "import ${servicePackageName}.${className}Service;\n" +
                    "import java.util.ArrayList;\n" +
                    "import java.util.HashMap;\n" +
                    "import work.soho.api.admin.vo.OptionVo;\n" +
                    "import work.soho.api.admin.request.BetweenCreatedTimeRequest;\n" +
                    "import java.util.stream.Collectors;\n" +        
                    "import work.soho.api.admin.vo.TreeNodeVo;" +
                    "\n" +
                    "/**\n" +
                    " * ${tableComment}Controller\n" +
                    " *\n" +
                    " * @author ${userName}\n" +
                    " * @date ${currentDate}\n" +
                    " */\n" +
                    "@RequiredArgsConstructor\n" +
                    "@RestController\n" +
                    "@RequestMapping(\"/admin/${fastLowerClassName}\" )\n" +
                    "public class ${className}Controller {\n" +
                    "\n" +
                    "    private final ${className}Service ${fastLowerClassName}Service;\n" +
                    "\n" +
                    "    /**\n" +
                    "     * 查询${tableComment}列表\n" +
                    "     */\n" +
//                    "    @PreAuthorize(\"@ss.hasPermi('admin:${fastLowerClassName}:list')\")\n" +
                    "    @GetMapping(\"/list\")\n" +
                    "    @Node(value = \"${fastLowerClassName}::list\", name = \"${tableComment}列表\")\n" +
                    "    public R<PageSerializable<${className}>> list(${className} ${fastLowerClassName}")
    //根据参数输出其他补充参数
    fields.each() {
        if(it.name == 'createdTime')
        out.print(
                ", BetweenCreatedTimeRequest betweenCreatedTimeRequest"
        )
    }

    out.println(                        ")\n" +
                    "    {\n" +
                    "        PageUtils.startPage();\n" +
                    "        LambdaQueryWrapper<${className}> lqw = new LambdaQueryWrapper<${className}>();")

    fields.each() {
        if(it.name == 'createdTime') {
            out.println(
                    "        lqw.ge(betweenCreatedTimeRequest!=null && betweenCreatedTimeRequest.getStartTime() != null, ${className}::getCreatedTime, betweenCreatedTimeRequest.getStartTime());\n" +
                            "        lqw.lt(betweenCreatedTimeRequest!=null && betweenCreatedTimeRequest.getEndTime() != null, ${className}::getCreatedTime, betweenCreatedTimeRequest.getEndTime());\n"
            )
        } else if(it.type == "String") { //字符串类型处理
            out.println("        if (StringUtils.isNotBlank(${fastLowerClassName}.get${it.name.capitalize()}())){\n" +
                    "            lqw.like(${className}::get${it.name.capitalize()} ,${fastLowerClassName}.get${it.name.capitalize()}());\n" +
                    "        }")
        } else {
            out.println("        if (${fastLowerClassName}.get${it.name.capitalize()}() != null){\n" +
                    "            lqw.eq(${className}::get${it.name.capitalize()} ,${fastLowerClassName}.get${it.name.capitalize()}());\n" +
                    "        }")
        }
    }

    out.println("        List<${className}> list = ${fastLowerClassName}Service.list(lqw);\n" +
            "        return R.success(new PageSerializable<>(list));\n" +
            "    }\n" +

            "\n" +
            "    /**\n" +
            "     * 获取${tableComment}详细信息\n" +
            "     */\n" +
//            "    @PreAuthorize(\"@ss.hasPermi('system:${fastLowerClassName}:query')\" )\n" +
            "    @GetMapping(value = \"/{id}\" )\n" +
            "    @Node(value = \"${fastLowerClassName}::getInfo\", name = \"${tableComment}详细信息\")\n" +
            "    public R<${className}> getInfo(@PathVariable(\"id\" ) Long id) {\n" +
            "        return R.success(${fastLowerClassName}Service.getById(id));\n" +
            "    }\n" +
            "\n" +
            "    /**\n" +
            "     * 新增${tableComment}\n" +
            "     */\n" +
//            "    @PreAuthorize(\"@ss.hasPermi('system:${fastLowerClassName}:add')\" )\n" +
            "    @PostMapping\n" +
            "    @Node(value = \"${fastLowerClassName}::add\", name = \"${tableComment}新增\")\n" +
            "    public R<Boolean> add(@RequestBody ${className} ${fastLowerClassName}) {"
    )

    //处理创建，更新时间
    fields.each() {
        if(it.name == 'createdTime') {
            out.println(
                    "       ${fastLowerClassName}.setCreatedTime(LocalDateTime.now());"
            )
        }
        if(it.name == 'updatedTime') {
            out.println(
                    "       ${fastLowerClassName}.setUpdatedTime(LocalDateTime.now());"
            )
        }
    }

    out.println(
            "        return R.success(${fastLowerClassName}Service.save(${fastLowerClassName}));\n" +
            "    }\n" +
            "\n" +
            "    /**\n" +
            "     * 修改${tableComment}\n" +
            "     */\n" +
            "    @PutMapping\n" +
            "    @Node(value = \"${fastLowerClassName}::edit\", name = \"${tableComment}修改\")\n" +
            "    public R<Boolean> edit(@RequestBody ${className} ${fastLowerClassName}) {"
    )

    //处理创建，更新时间
    fields.each() {
        if(it.name == 'updatedTime') {
            out.println(
                    "       ${fastLowerClassName}.setUpdatedTime(LocalDateTime.now());"
            )
        }
    }

    out.println(
            "        return R.success(${fastLowerClassName}Service.updateById(${fastLowerClassName}));\n" +
            "    }\n" +
            "\n" +
            "    /**\n" +
            "     * 删除${tableComment}\n" +
            "     */\n" +
            "    @DeleteMapping(\"/{ids}\" )\n" +
            "    @Node(value = \"${fastLowerClassName}::remove\", name = \"${tableComment}删除\")\n" +
            "    public R<Boolean> remove(@PathVariable Long[] ids) {\n" +
            "        return R.success(${fastLowerClassName}Service.removeByIds(Arrays.asList(ids)));\n" +
            "    }" )


    //判断处理选项action判断处理选项action
    if(getExtendData(tableComment, "option", null) != null)  {
        def optionKeyCol = getOptionKeyCol(tableComment, fields)
        def optionValCol = getOptionValCol(tableComment, fields)
        out.println(
                "\n    /**\n" +
                        "     * 获取该表options${optionKeyCol}\n" +
                        "     *\n" +
                        "     * @return\n" +
                        "     */\n" +
                        "    @GetMapping(\"options\")\n" +
                        "    @Node(value = \"${fastLowerClassName}::options\", name = \"${tableComment}Options\")\n" +
                        "    public R<HashMap<Integer, String>> options() {\n" +
                        "        List<${className}> list = ${fastLowerClassName}Service.list();\n" +
                        "        List<OptionVo<${optionKeyCol.javaType}, ${optionValCol.javaType}>> options = new ArrayList<>();\n" +
                        "\n" +
                        "        HashMap<Integer, String> map = new HashMap<>();\n" +
                        "        for(${className} item: list) {\n" +
                        "            map.put(item.get${optionKeyCol.capitalKeyName}(), item.get${optionValCol.capitalKeyName}());\n" +
                        "        }\n" +
                        "        return R.success(map);\n" +
                        "    }"
        )
    }

    //输出tree接口
    def frontHome = getTableFrontHome(table)
    if(frontHome == 'tree') {
        out.println(
                "\n    @GetMapping(\"tree\")\n" +
                "    public R<List<TreeNodeVo>> tree() {\n" +
                "        List<${className}> list = ${fastLowerClassName}Service.list();\n" +
                "        List<TreeNodeVo<Integer, Integer, Integer, String>> listVo = list.stream().map(item->{\n" +
                "            return new TreeNodeVo<>(item.getId(), item.getId(), item.getParentId(), item.getTitle());\n" +
                "        }).collect(Collectors.toList());\n" +
                "\n" +
                "        Map<Integer, List<TreeNodeVo>> mapVo = new HashMap<>();\n" +
                "        listVo.stream().forEach(item -> {\n" +
                "            if(mapVo.get(item.getParentId()) == null) {\n" +
                "                mapVo.put(item.getParentId(), new ArrayList<>());\n" +
                "            }\n" +
                "            mapVo.get(item.getParentId()).add(item);\n" +
                "        });\n" +
                "\n" +
                "        listVo.forEach(item -> {\n" +
                "            if(mapVo.containsKey(item.getKey())) {\n" +
                "                item.setChildren(mapVo.get(item.getKey()));\n" +
                "            }\n" +
                "        });\n" +
                "        return R.success(mapVo.get(0));\n" +
                "    }"
        )
    }

    out.println(        "}")
}

////////////////////////////////// 以下为公共函数

//def create
def calcFields(table) {
    DasUtil.getColumns(table).reduce([]) { fields, col ->
        def spec = Case.LOWER.apply(col.getDataType().getSpecification())
        def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
        def dbTypeStr = dbTypeMapping.find { p, t -> p.matcher(spec).find() }.value
        def isUnsignedMatch = dbUnsignedMapping.find {p, t -> p.matcher(spec).find() }
        def isUnsigned = isUnsignedMatch == null ? false : true
        def frontType = getFrontType(dbTypeStr, col.getComment())
        def frontMax = new BigDecimal("0")
        def frontStepStr = ""
        //外链表信息
        def dbForeignName = "";
        def capitalForeignName = "";
        def javaForeignName = "";
        def javaType = getJavaType(dbTypeStr, col.getComment())
        def isFilter = getExtendData(col.getComment(), 'isFilter', 'false');
        def frontName = capitalName(getExtendData(col.getComment(), 'frontName', ''))
        if(frontName == '') {
            frontName = capitalName(col.getName());
        }

        if(frontType == 'select' || frontType == 'treeSelect') {
            dbForeignName = getForeignTable(col.getComment())
            if(dbForeignName) {
                capitalForeignName = capitalName(dbForeignName).replace(" ", "")
                javaForeignName =  javaName(dbForeignName, false)
            }
        }

        if(frontType == 'number') {
            //计算最大值
            frontMaxStr = String.format("%1\$" + (col.getDataType().getLength() - ((col.getDataType().getScale()>0)?col.getDataType().getScale() : 0)) + "s", "9").replace(' ', '9')
            if(col.getDataType().getScale()>0) {
                frontMaxStr += "."+String.format("%1\$" + (col.getDataType().getScale()) + "s", "9").replace(' ', '9')
            }
            frontMax = new BigDecimal(frontMaxStr);
            //计算step
            if(col.getDataType().getScale()>0) {
                frontStepStr = "0."+String.format("%1\$" + (col.getDataType().getScale()) + "s", "1").replace(' ', '0')
            }
        } else {
            frontMax = null
        }


        fields += [[
                           name : javaName(col.getName(), false), //小驼峰名称
                           capitalName: capitalName(col.getName()), //带空格的大驼峰名称
                           capitalKeyName: capitalName(col.getName()).replace(" ", ""), //大驼峰名称
                           dbColName: col.getName(), //db原始名称
                           type : typeStr, //对应的java数据了些
                           frontType: frontType, // 
                           frontName: frontName, //前端展示名称
                           frontMax: frontMax, //前端展示最大数
                           frontStep: frontStepStr, //前端数字展示 step
                           isFilter: isFilter, //是否为列表页条件筛选字段
                           dbType: dbTypeStr, //数据库类型
                           dbUnsigned: isUnsigned, //数据库字段为无符号类型
                           comment: col.getComment(), //字段注释
                           annos: "",  //？？
                           length: col.getDataType().getLength(), //字段长度
                           scale: col.getDataType().getScale(), //小数部分长度
                           frontLength: (frontType == 'number') ? col.getDataType().getLength() + 1 : col.getDataType().getLength(), //前端校验长度
                           defaultValue: col.getDefault(), //字段默认值
                           isNotNull: col.isNotNull(), //是否可以为空
                           specification: col.getDataType().getSpecification(), //只用来做调试，请勿使用
                           dbForeignName: dbForeignName, //外建db名
                           capitalForeignName: capitalForeignName, //外建大驼峰
                           javaForeignName: javaForeignName, //java外链表名
                           javaType: javaType, //字段对应的java类型
                   ]]
    }
}

def javaName(str, capitalize) {
    if(str  == null) {
        return null;
    }
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

def capitalName(str) {
    if(str == null) {
        return null;
    }
    com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join(" ")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, " ")
}

/**
 * 获取前端类型
 *
 * @param dbType
 * @param comment
 * @return
 */
def getFrontType(dbType, comment) {
    def frontType = getExtendData(comment, 'frontType', null);
    if(frontType) {
        return frontType;
    }
    switch (dbType) {
        case "int":
        case "tinyint":
        case "smallint":
        case "mediumint":
        case "bigint":
        case "float":
        case "double":
        case "decimal":
            frontType = "number"
            break;
        default:
            frontType = "text";
            break;
    }
    return frontType;
}

/**
 * 获取外链表
 *
 * @param comment
 * @return
 */
def getForeignTable(comment) {
    def foreign = getExtendData(comment, 'foreign', null)
    if(foreign) {
        String[] parts = foreign.split("~")
        if(parts && parts.length>=1) {
            def fid = parts[0]
            String[] tableParts = fid.split("\\.")
            if(tableParts.length>0) {
                return tableParts[0]
            }
        }
    }
    return null;
}

/**
 * 获取关联表大驼峰名
 */
def getForeignTableCapitalKey(comment) {
    def capita = getForeignTable(comment)
    if(capita) {
        return capitalName(capita).replace(" ", "");
    }
    return null;
}

/**
 * 获取前端校验最小值
 */
def getFrontMin(it) {
    def min = 0
    def minStr = getExtendData(it.comment,"min", null)
    if(minStr != null) {
        return Integer.valueOf(minStr)
    }

    //检查表单类型
    def frontType = getExtendData(it.comment, 'frontType', 'text')
    if(frontType != 'text') {
        return null;
    }

    if(it.dbUnsigned) {
        //无符号
        switch (it.dbType) {
            case "tinyint":
            case "smallint":
            case "mediumint":
            case "int":
            case "bigint":
                min = 0;
                break;
            default:
//                min = it.length;
                break;
        }
    } else {
        switch (it.dbType) {
            case "tinyint":
                min = -128
                break;
            case "smallint":
                min = -32768;
                break;
            case "mediumint":
                min = 	-8388608;
                break;
            case "int":
                min = -2147483648;
                break;
            case "bigint":
                min = -9007199254740991;  //该值为Js最大值
                break;
            default:
//                min = it.length;
                break;
        }
    }
    return min;
}

/**
 * 获取前端校验最小值
 */
def getFrontMax(it) {
    def max = it.length
    //dbUnsigned
    def maxStr = getExtendData(it.comment,"max", null)
    if(maxStr != null) {
        //如果指定直接使用指定值
        return Integer.valueOf(maxStr)
    }

    //检查表单类型
    def frontType = getExtendData(it.comment, 'frontType', 'text')
    if(frontType != 'text') {
        return null;
    }

    if(it.dbUnsigned) {
        //无符号
        switch (it.dbType) {
            case "tinyint":
                max = 255
                break;
            case "smallint":
                max = 	65535;
                break;
            case "mediumint":
                max = 16777215;
                break;
            case "int":
                max = 4294967295;
                break;
            case "bigint":
                max = 9007199254740992;  //该值为Js最大值
                break;
            default:
                max = it.length;
                break;
        }
    } else {
        switch (it.dbType) {
            case "tinyint":
                max = 127
                break;
            case "smallint":
                max = 32767;
                break;
            case "mediumint":
                max = 8388607;
                break;
            case "int":
                max = 2147483647;
                break;
            case "bigint":
                max = 9007199254740992;  //该值为Js最大值
                break;
            default:
                max = it.length;
                break;
        }
    }

    return max;
}

/**
 * 查找domain命名空间
 *
 * @param dir
 */
def findDomainPackageName(dir) {
    return findPackageName(new File(dir.getParent() + "/domain"))
}

/**
 * 查找service命名空间
 *
 * @param dir
 */
def findServicePackageName(dir) {
    return findPackageName(new File(dir.getParent() + "/service"))
}

/**
 * 查找指定目录现有的命名空间
 *
 * @param dir
 * @return
 */
def findPackageName(dir) {
    if(dir != null && dir.isDirectory()) {
        File[] files = dir.listFiles();
        if(files != null && files.length>0) {
            for (File item:files) {
                if(item.isFile()) {
                    List<String> lines = Files.readLines(item, StandardCharsets.UTF_8);
                    //查找命名空间
                    for (String line: lines) {
                        line = line.trim();
                        if(line.startsWith("package")) {
                            line = line.split(" ")[1];
                            line = line.replace(";", "")
                            line = line.trim();
                            return line;
                        }
                    }
                }
            }
        }
    }
    return ""
}

/**
 * 首字母小写
 * @param s
 * @return
 */
def toLowerCaseFirstOne(String s){
    if(Character.isLowerCase(s.charAt(0)))
        return s;
    else
        return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
}

/**
 * 转换成中划线
 *
 * @param s
 * @return
 */
def toStrikethrough(String str) {
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it) }
            .join("-")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    return s
}

/**
 * 获取当前时间
 * @return
 */
def currentDate() {
    Date d = new Date();
    System.out.println(d);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String dateNowStr = sdf.format(d);
    return dateNowStr;
}

/**
 * 获取注解选项
 *
 * @param comment
 * @return
 */
def getOptions(String comment) {
    if(comment == null) {
        return []
    }
    String[] parts = comment.split(";");
    if(parts.length<2) {
        return null;
    }
//    String colmenName = parts[0];
    parts = parts[1].split(",");
    HashMap<String, String> dataMap = new HashMap<>();
    for (String item: parts) {
        String[] kv = item.split(":");
        if(kv.length == 2) {
            dataMap.put(kv[0].trim(), kv[1]);
        } else {
            dataMap.put(kv[0], kv[0]);
        }
    }
    return dataMap;
}

/**
 * 获取前端展示类型
 *"frontType"
 * @param comment
 */
def getExtendData(String comment, String key, String defaultVal) {
    String type = defaultVal
    if(comment == '' || comment == null) {
        return defaultVal
    }
    String[] parts = comment.split(";");
    if(parts.length<3) {
        return type;
    }
    if(parts.length>=3) {
        parts = parts[2].split(",");
        HashMap<String, String> dataMap = new HashMap<>();
        for (String item: parts) {
            String[] kv = item.split(":");
            if(kv.length == 2) {
                dataMap.put(kv[0].trim(), kv[1]);
            }
        }
        if(dataMap.containsKey(key)) {
            type = dataMap.get(key)
        }
    }
    return type
}

/**
 * 获取表前端首页类型
 *
 * @param table
 * @return
 */
def getTableFrontHome(table) {
    def fontType = getExtendData(table.getComment(), 'frontHome', 'list')
    return fontType;
}

/**
 * 获取制定字段类型
 *
 * @param name
 * @param fileds
 */
def getCol(name, fileds) {
    def col = null;
    fileds.each() {
        if(name == it.dbColName) {
            col = it;
        }
    }
    return col;
}

/**
 * 获取表选项key
 *
 * @param comment
 * @param fileds
 * @return
 */
def getOptionKeyCol(comment, fileds) {
    def optionStr = getExtendData(comment, 'option', null)
    if(optionStr == null) {
        return null
    }
    String[] parts = optionStr.split("~")
    if(parts.length>0)  {
        def col = getCol(parts[0], fileds)
        if(col == null) {
            return null;
        }
        return col;
    }
    return null;
}

/**
 * 获取表选项key
 *
 * @param comment
 * @param fileds
 * @return
 */
def getOptionValCol(comment, fileds) {
    optionStr = getExtendData(comment, 'option', null)
    if(optionStr == null) {
        return null
    }
    String[] parts = optionStr.split("~")
    if(parts.length>1)  {
        def col = getCol(parts[1], fileds)
        if(col == null) {
            return null;
        }
        return col;
    }
    return null;
}

/**
 * 根据字段类型注解获取java类型
 *
 * @param dbType
 * @param comment
 */
def getJavaType(dbType, comment) {
    def javaType = getExtendData(comment, "javaType", null)
    if(javaType != null)  {
        return javaType
    }
    //查看注解有没有指定后段类型
    switch (dbType) {
        case 'int':
        case 'tinyint':
        case 'smallint':
        case 'mediumint':
            javaType = "Integer"
            break;
        case 'bigint':
            javaType = "BigInteger"
            break;
        case 'bit':
            javaType = 'Boolean'
            break;
        case 'data':
        case 'datetime':
        case 'timestamp':
            javaType = "LocalDateTime"
            break;
        case 'float':
            javaType = "Float"
            break
        case 'double':
            javaType = "Double"
            break;
        default:
            javaType = "String"
            break;
    }
    return javaType
}
